<?php
/**
 * Created by PhpStorm.
 * User: 汪旭
 * Date: 2019/2/18
 * Time: 15:48
 */

namespace app\wap\controller;

use think\Controller;

class Weather extends Controller
{
    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');
    }

    private $key = 'de0cd087fee1481180a5ebeeb61dc6da';//平台个人秘钥
//    private $key = '8b32733d8a71441f9ba42febfa48bae2';//平台个人秘钥2

    //天气定时查询缓存
    public function index($city_id=0){
        $url = 'https://free-api.heweather.net/s6/weather/forecast';//请求地址
        $where  = [];
        $data   = [];
        $where['deleted'] = 0;
        $where['groupid'] = ['NEQ',0];

        if($city_id>0){
            $where['id'] = $city_id;
        }else{
            //初始化
            cache('Weather',array());
        }

        //查询当前数据库开启的城市城市
        $city = db('city')->where($where)->select();
        foreach ($city as $value){
            $location = [];
            //组装参数
            if(empty($value['lng']) || empty($value['lat'])){//判断是否存在经纬度
                $location['location'] = !empty($value['eng_name'])?$value['eng_name']:$value['name'] ;
            }else{
                $location['location'] = $value['lng'].','.$value['lat'] ;
            }
            $location['key'] = $this->key;
            //转换参数格式
            $location = http_build_query($location);
            $da = $this->post_curl($url,$location);
            //将天气数据根据当前城市id存储
            $jsonArr = json_decode($da,true)['HeWeather6'][0];
            //加入城市id
            $jsonArr['city_id'] = $value['id'];
            $jsonArr['kbx_id'] = !empty($value['kbx_id']) ? $value['kbx_id'] : '';
            $data[$value['id']] = $jsonArr;
        }

        if($city_id>0){
            $das = cache('Weather');
            $das[$city_id] = $data[$city_id];
            $res_data = $das;
        }else{
            $res_data = $data;
        }

        //存入缓存
        cache('Weather',$res_data);

        return '执行完毕';

    }

    //天气查询缓存
    public function city_query(){
        //取出缓存数据
        $das= cache('Weather');

        $post = request()->post();
        $city_id = $post['city_id'];

        if($city_id==91){
            $city_id = 71;//黄石国家公园转向盐湖城
        }

        if (empty($das) || isset($das[$city_id])){
            $this->index($city_id);
            $das = cache('Weather');
        }

        $c=[];
        foreach ($das as $key=>$value){
            //判断取出当前查询城市天气数据
            if ($city_id == $key){
                if($value['status']!=='ok'){
                    return json(['msg'=>'没有查询到城市信息','data'=>$value,'code'=>400]);
                }
                //循环天气数据
                foreach ($value['daily_forecast'] as $v){
                    $c[] = [
                        'city_name' => $value['basic']['location'],
                        'city_id' => $value['city_id'],
                        'date' => $v['date'],
                        'cond_code_d' => $v['cond_code_d'],
                        'cond_code_n' => $v['cond_code_n'],
                        'cond_txt_d' => $v['cond_txt_d'],
                        'cond_txt_n' => $v['cond_txt_n'],
                        'tmp_max' => $v['tmp_max'],
                        'tmp_min' => $v['tmp_min'],
                        'hum' => isset($v['hum']),
                        'pcpn' => isset($v['pcpn']),
                        'pop' => isset($v['pop']),
                    ];
                }
                break;
            }
        }
        //判断是否有数据
        if (!empty($c)){
            return json(['msg'=>'查询成功','data'=>$c,'code'=>0]);
        }else{
            return json(['msg'=>'没有查询到城市信息','data'=>$c,'code'=>400]);
        }
    }


    public function showcache(){

        $das = cache('Weather');

        echo "<pre>";
        var_dump($das);
        echo "</pre>";
        exit;
    }



    public function post_curl($url, $post_data) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);//数据包发送
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($ch);
        if($error=curl_error($ch)){
            return $error;
        }
        curl_close($ch);
        return $response;
    }

}